﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Business
{
    public partial class ProjectTeam
    {
        public static Common.ERROR_CODE.ERROR_CODE_ITEMS_UPDATE Update(
            ref string messageError,
            ref List<ProjectTeam> listOldPT,
            ref Common.UserInfo UserInfo)
        {
            DataClassesDataContext context = null;
            try
            {
                context = new DataClassesDataContext(Common.Global.GetConnectionInfo().ConnectionStringSQL);

                listOldPT = listOldPT.GroupBy(x => new { x.ProjectID, x.ProjectMechanicism, x.POSM })
                  .Select(group => group.First()).ToList();

                foreach (var item in listOldPT)
                {
                    var clean = context.ProjectTeams.Where(
                        p => p.ProjectID == item.ProjectID
                        && p.ProjectMechanicism == item.ProjectMechanicism
                        && p.ProjectChannel == item.ProjectChannel);
                    context.ProjectTeams.DeleteAllOnSubmit(clean);
                }

                //init
                List<ProjectTeam> listNewPT = new List<ProjectTeam>();
                //add new
                foreach (ProjectTeam item in listOldPT)
                {
                    ProjectTeam pt = new ProjectTeam();
                    pt.TeamID = item.TeamID;
                    pt.ProjectID = item.ProjectID;
                    pt.ProjectMechanicism = item.ProjectMechanicism;
                    pt.ProjectChannel = item.ProjectChannel;
                    pt.POSM = item.POSM;
                    pt.Status = (int)Common.STATUS_CODE.ROW_STATUS.ACTIVE;
                    pt.CreatedBy = UserInfo.UserID;
                    pt.CreatedDateTime = DateTime.Now;
                    pt.RowVersion = 1;

                    listNewPT.Add(pt);
                    context.ProjectTeams.InsertOnSubmit(pt);
                }

                context.SubmitChanges();

                listOldPT = listNewPT;

                return Common.ERROR_CODE.ERROR_CODE_ITEMS_UPDATE.SUCCESS;
            }
            catch
            {
                messageError = Common.EnumUtils.stringValueOf(Common.ERROR_CODE.ERROR_CODE_ITEMS_SELECT.SYSTEM_ERROR);
                return Common.ERROR_CODE.ERROR_CODE_ITEMS_UPDATE.SYSTEM_ERROR;
            }
            finally
            {
                context = null;
            }
        }
    }
}
